package com.lyun.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.lyun.bo.TodayBestBo;
import com.lyun.common.BaseContext;
import com.lyun.common.EveryConstant;
import com.lyun.common.HuanxinTemplate;
import com.lyun.common.MyBusinessException;
import com.lyun.constants.HXConstants;
import com.lyun.dto.RecommendationDTO;
import com.lyun.dto.StrangerQuestionsDTO;
import com.lyun.pojo.LoveValue;
import com.lyun.pojo.User;
import com.lyun.service.LoveValueService;
import com.lyun.service.SettingService;
import com.lyun.service.TanhuaService;
import com.lyun.service.UserService;
import com.lyun.vo.PageVO;
import com.lyun.vo.TodayBestVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

@DubboService
public class TanhuaServiceImpl implements TanhuaService {

    @DubboReference
    private UserService userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private LoveValueService loveValueService;

    @Resource
    private HuanxinTemplate huanxinTemplate;

    @DubboReference
    private SettingService settingService;

    /**
     * 获取今日佳人
     *
     * @param bo
     * @return
     */
    @Override
    public TodayBestVO todayBest(TodayBestBo bo) {

        User user = userService.getById(bo.getId());

        //todo 用 mq
        user.setLastLogin(String.valueOf(System.currentTimeMillis()));
        userService.updateById(user);

        //先查redis
        String o = redisTemplate.opsForValue().get(EveryConstant.TODAY_BEST_PREFIX + bo.getId());
        TodayBestVO redisVo = JSON.parseObject(o, TodayBestVO.class);

        if (Objects.nonNull(redisVo)) {
            return redisVo;
        }

        //根据算法 获取一个 “佳人”
        User bestUser = userService.getTodayBest(user);

        //新建lovevalue
        LoveValue loveValue = new LoveValue();
        loveValue.setFromId(bo.getId());
        loveValue.setToId(bestUser.getId());

        //根据id和toId查询缘分值
        LoveValue value = loveValueService.selectValueByFromIdAndToId(bo.getId(), bestUser.getId());
        if (value == null) {
            Random ran = new Random();
            int ranNum = ran.nextInt(100) + 1;
            loveValue.setFateValue(ranNum);
            //保存lovevalue
            loveValueService.insertValue(loveValue);
        } else {
            loveValue.setFateValue(value.getFateValue());
        }

        //给vo赋值
        TodayBestVO vo = new TodayBestVO();
        BeanUtils.copyProperties(bestUser, vo);
        vo.setAvatar(bestUser.getHeader());
        String tags = bestUser.getTags();

        if (tags == null) {
            vo.setTags(null);
        } else {
            List<String> list = StrUtil.split(tags, ",");
            vo.setTags(list);
        }

        vo.setFateValue(loveValue.getFateValue());

        LocalDateTime now = LocalDateTime.now();
        LocalTime midnight = LocalTime.MIDNIGHT;
        LocalDateTime tomorrowMidnight = now.toLocalDate().plusDays(1).atTime(midnight);

        // 计算距离明天凌晨12点的秒数
        int ttl = (int) now.until(tomorrowMidnight, ChronoUnit.SECONDS);

        redisTemplate.opsForValue().set(EveryConstant.TODAY_BEST_PREFIX + bo.getId(), JSON.toJSONString(vo), ttl, TimeUnit.SECONDS);

        return vo;
    }

    @Override
    public PageVO<TodayBestVO> getRecommendationList(Long id, RecommendationDTO dto) {
        return userService.getRecommendationList(id, dto);
    }

    @Override
    public void replyQuestions(StrangerQuestionsDTO dto) {
        Long currentUserId = BaseContext.getCurrentId();
        User user = userService.getById(currentUserId);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", currentUserId);
        map.put("huanXinId", HXConstants.HX_HEADER + currentUserId);
        map.put("nickname", user.getNickname());
        map.put("strangerQuestion", strangerQuestions(dto.getUserId()));
        map.put("reply", dto.getReply());
        String message = JSON.toJSONString(map);
        //2.调用template通过环信发送消息
        Boolean aBoolean = huanxinTemplate.sendMsg(HXConstants.HX_HEADER + dto.getUserId(), message);
        if (!aBoolean) {
            throw new MyBusinessException("系统异常，请稍后重试");
        }
    }

    public String strangerQuestions(Long userId) {
        return settingService.selectQuestionById(userId);
    }
}
